# coding:utf-8
"""
Created on 2013-8-8

@author: Xen
"""
import base64
import time
import string
import random
import struct
import datetime
from bson.objectid import ObjectId
from tornado.log import app_log

import config

try:
    import xml.etree.cElementTree as ElementTree
except ImportError:
    import xml.etree.ElementTree as ElementTree


def int2hex(num):
    return str(hex(int(num))).replace('0x', '').replace('L', '')


def hex2int(shex):
    return int('0x' + shex, 16)


def str2int_list(str_list):
    int_list = [int(s) for s in str_list]
    return int_list


def hex2int_list(hex_list):
    int_list = [hex2int(shex) for shex in hex_list]
    return int_list


def str2ts(dts, fmt='%Y-%m-%d %H:%M'):
    return time.mktime(time.strptime(dts, fmt))


def ts2str(ts, fmt='%Y-%m-%d %H:%M'):
    return time.strftime(fmt, time.localtime(ts))


# datetime格式的0区utc时间
def datetime_utc():
    return datetime.datetime.utcnow()


# 字符串转datetime格式时间
def str2datetime(dstr, fmt='%Y-%m-%d %H:%M:%S'):
    return datetime.datetime.strptime(dstr, fmt)


# 时间搓转datetime格式
def ts2datetime(ts):
    return datetime.datetime.fromtimestamp(ts)


# 时间搓转utcdatetime格式
def ts2utcdatetime(ts):
    return datetime.datetime.utcfromtimestamp(ts)


# datetime 转时间搓
def datetime2ts(dts, fmt='%Y-%m-%d %H:%M:%S'):
    return time.mktime(time.strptime(dts.strftime(fmt), fmt))


# datetime 转时间搓 当前时区
def datetime2tscurrent(dts, fmt='%Y-%m-%d %H:%M:%S'):
    if isinstance(dts, datetime.datetime):
        return int(time.mktime(time.strptime(dts.strftime(fmt), fmt)) - time.timezone)
    else:
        return dts


# id 转换objectid
def id2objectid(_id):
    if isinstance(_id, ObjectId):
        return _id
    if str(_id).isdigit():
        return int(_id)
    else:
        return ObjectId(_id)


# objectid 换取数字编号
def objectid2num(_id):
    sting_byte = struct.pack(">i", 1211216)[0]
    id_num = ts2str(datetime2tscurrent(_id.generation_time), fmt="%Y%m%d%H%M") + str(
        struct.unpack(">i", sting_byte + _id.__getstate__()[9:12])[0]).zfill(8)

    return id_num


def upfile_dir(fname):
    ts = hex2int(fname[:len(fname) - 4]) // 1000
    return '/' + time.strftime('%y%m', time.localtime(ts)) + '/' + fname

def float_filter(num):
    return float("%.2f" % float(num))

def upfile_path(fname):
    return config.gconf['imgmain'] + upfile_dir(fname)


def sxml2dict(sxml):
    redict = {}
    root = ElementTree.fromstring(sxml)
    for child in root:
        value = child.text
        redict[child.tag] = value
    return redict


def dict2sxml(obj):
    xml = ["<xml>"]
    for k, v in obj.items():
        if v.isdigit():
            xml.append("<{0}>{1}</{0}>".format(k, v))
        else:
            xml.append("<{0}><![CDATA[{1}]]></{0}>".format(k, v))
    xml.append("</xml>")
    return "".join(xml)


def group(lst, block):
    return [lst[i:i + block] for i in range(0, len(lst), block)]


def order_no(ts=0):
    ts = int(ts) if ts else (time.time())
    return ts2str(ts, '%Y%m%d') + str(random.randint(10000000, 99999999))


def unique_name():
    s1 = int2hex(time.time() * 1000)
    s2 = int2hex(random.randint(100000, 999999))
    return s2 + s1


def import_name(modulename, name):
    try:
        module = __import__(modulename, fromlist=[name])
    except ImportError as e:
        print('import', modulename, e)
        raise e
    return getattr(module, name)


def random_list(num, docs):
    rid = []
    for i in range(len(docs)):
        r = random.randrange(0, len(docs))
        if r not in rid:
            rid.append(r)
    return [docs[j] for j in rid[:num]]


def create_noncestr(length=16, rule=string.ascii_letters + string.digits):
    return ''.join(random.sample(rule, length))


# 生成邀请码
def create_code(length=8, chars=string.ascii_letters + string.digits):
    return ''.join(
        random.choice(chars.replace('l', '').replace('I', '').replace('0', '').replace('o', '').replace('O', ''))
        for _ in range(length))


def trans_avg_eva(num):
    """
    平均评价分转换函数
    :param num:
    :return:
    """
    intpart = int(num)
    res = intpart + 0.5 if num - intpart else intpart
    return round(res, 1)


def query2list(query, mode='query'):
    """
    sql query对象转list
    """
    return [i.to_dict() for i in query] if mode == "query" else [i for i in query]


def httpdate_rfc1123(dt):
    """
    Return a string representation of a date according to RFC 1123
    (HTTP/1.1).
    GMT 格式字符串 (RFC 1123)，如 Wed, 29 Oct 2014 02:26:58 GMT
    The supplied date must be in UTC.
    """

    weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][dt.weekday()]
    month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
             'Oct', 'Nov', 'Dec'][dt.month - 1]
    return '%s, %02d %s %04d %02d:%02d:%02d GMT' % \
           (weekday, dt.day, month, dt.year, dt.hour, dt.minute, dt.second)


